package androidcamp.socialfitnesstracker;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ShareCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidcamp.socialfitnesstracker.data.Goal;
import androidcamp.socialfitnesstracker.data.ListListener;

public class Goals extends Activity {
    
    private ListView goalsListView;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.goals_layout);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.goals, menu);

		ShareCompat.IntentBuilder shareIntentBuilder = ShareCompat.IntentBuilder
				.from(this).setText("I want to run 10 miles this week!")
				.setType("text/plain");
		ShareCompat.configureMenuItem(menu, R.id.share, shareIntentBuilder);

        goalsListView = (ListView) findViewById(R.id.goalsList);
        ListListener<Goal> listener = new ListListener<Goal>() {
            public void itemAdded(int index, Goal item) {
                ArrayAdapter<Goal> adapter = new ArrayAdapter<Goal>(Goals.this,
                        R.layout.goal_text_view, MockDB.get().getAllGoals());
                Goals.this.goalsListView.setAdapter(adapter);
            }
        };
        MockDB.get().addGoalListener(listener);
        // call to initially add goals
        listener.itemAdded(0, null); // TODO: janky

        goalsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Goal theGoal = MockDB.get().getAllGoals().get(i);
                Intent intent = new Intent(Goals.this, GoalsDetail.class);
                intent.putExtra("THE_GOAL", theGoal);
                Goals.this.startActivity(intent);
            }
        });
        
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
		Log.i("item selected", "item selected");
	    switch (item.getItemId()) {
	        case R.id.add:
	        	Intent i = new Intent(this, GoalsPrompt.class);
                startActivity(i);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
}
